<?php
/**
 * (ajax) 发货需求
 */

namespace App\Admin\Ajax\CustomerDelivery;

use App\Models\Basics\SysArea;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysPlat;
use App\Models\CustomerDelivery\CustomerDelivery;
use App\Models\CustomerDelivery\CustomerDeliveryDetail;
use App\Models\CustomerDelivery\CustomerOrder;
use App\Models\CustomerDelivery\CustomerOrderDetails;
use App\Models\Inventory\AreaCn;
use App\Models\Inventory\InventoryCn;
use App\Models\Inventory\PublicCn;
use App\Models\Inventory\Timely;
use App\Models\Product\ProductSku;
use App\Models\Sys\Logs;
use App\Util\SerialNo;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;

class DeliveryDemandAjax
{

    /**
     * 创建发货
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function doCreateDelivery($param){

        if (empty($param)) return response()->json(['status' => false, 'message' => '参数异常!']);
        //组装参数
        $dataParams = [];
        foreach ($param as $k => $v){
            $dataParams[$v['order_no']][$v['delivery_type']][$v['psku_id']] = [
                'order_detail_id' => $v['order_detail_id'] ?? 0,
                'apply_num'       => $v['apply_num'] ?? 0,
                'apply_remarks'   => $v['apply_remarks'] ?? '',
                'account_id'      => $v['account_id'] ?? 0,
                'seller_sku'      => $v['seller_sku'] ?? '',
                'warehouse_id'    => $v['warehouse_id'] ?? 0,
            ];
        }
        if (empty($dataParams)) return response()->json(['status' => false, 'message' => '参数不能为空!']);

        //发货
        foreach ($dataParams as $order_no => $delivery){

            //验证订单(发货站点/发货国家)
            $customerOrderObj = CustomerOrder::query()->where('order_no', $order_no)->lockForUpdate()->first();
            if (!$customerOrderObj) continue;

            //发货方式
            foreach ($delivery as $deliveryType => $val){
                switch ($deliveryType){
                    case CustomerDelivery::DELIVERY_TYPE_FBA:
                        $data = $this->doFBADelivery($deliveryType, $customerOrderObj, $val); //FBA
                        break;
                    case CustomerDelivery::DELIVERY_TYPE_ABROAD:
                        $data = $this->doWarehouseDelivery($deliveryType, $customerOrderObj, $val); //海外仓
                        break;
                    case CustomerDelivery::DELIVERY_TYPE_CN:
                        $data = $this->doCnDelivery($deliveryType, $customerOrderObj, $val); //国内仓
                        break;
                    default:
                        return response()->json(['status' => false, 'message' => '发货方式异常!']);
                }
            }
        }

        return response()->json(['status' => $data['status'] ?? false, 'message' => $data['message'] ?? '异常!']);
    }

    /**
     * 创建FBA发货单
     * @param $delivery_type
     * @param $customerOrderObj
     * @param $detail
     * @return array
     */
    private function doFBADelivery($delivery_type, $customerOrderObj, $detail){


        //客户订单
        if(!$customerOrderObj) return ['status' => false, 'message' => '客户订单异常!'];
        //发货站点
        if(!$customerOrderObj->area_id) return ['status' => false, 'message' => '发货站点异常!'];
        //发货国家
        if(!$customerOrderObj->country_id) return ['status' => false, 'message' => '发货国家异常!'];

        //验证实际发货单号(批次)
        $_deliveryOrderNo = CustomerDeliveryDetail::query()
            ->where(['order_no' => $customerOrderObj->order_no])
            ->orderByDesc('id')
            ->limit(1)
            ->value('delivery_order_no');
        $deliveryOrderNo = formatStrOrderNo($_deliveryOrderNo) ?? $customerOrderObj->order_no;

        //组装明细数据
        $deliveryDetail = [];
        foreach ($detail as $pskuId => $item){
            $orderDetailObj = CustomerOrderDetails::query()->find($item['order_detail_id']);
            if($orderDetailObj->status == CustomerOrderDetails::ORDER_DELIVERY_CANCEL) continue;

            //发货明细数据
            $deliveryDetail[$customerOrderObj->order_no][] = [
                'order_no'          => $customerOrderObj->order_no, //订单号
                'delivery_order_no' => $deliveryOrderNo, //实际发货订单号
                'order_detail_id'   => $item['order_detail_id'], //订单明细id
                'psku_id'           => $pskuId ?? 0,
                'seller_sku'        => $item['seller_sku'] ?? '',
                'plat_id'           => $customerOrderObj->plat_id,
                'plat_sku'          => $orderDetailObj->plat_sku ?? '',
                'apply_num'         => $item['apply_num'] ?? 0,
                'account_id'        => $item['account_id'] ?? 0,
                'apply_remarks'     => $item['apply_remarks'] ?? '',
                'status'            => CustomerDeliveryDetail::STATUS_DELIVERY_NO, //FBA发货,默认发货明细状态 (3:待发货)
                'delivery_type'     => $delivery_type,
            ];
        }
        if(!$deliveryDetail) return ['status' => false, 'message' => '暂无可发货产品!'];

        //DB::beginTransaction();
        //try{
            //发货
            foreach($deliveryDetail as $details){
                //创建发货单
                $deliveryNo = SerialNo::getOSANo();
                $delivery = CustomerDelivery::query()->create([
                    'delivery_no'   => $deliveryNo,
                    'order_no'      => $customerOrderObj->order_no,
                    'order_at'      => $customerOrderObj->order_at,
                    'plat_id'       => $customerOrderObj->plat_id,
                    'area_id'       => $customerOrderObj->area_id,
                    'country_id'    => $customerOrderObj->country_id,
                    'seller_id'     => Admin::user()->id ?? 0,
                    'delivery_type' => $delivery_type,
                    'status'        => CustomerDelivery::STATUS_DELIVERY_NO,  //FBA发货,默认发货单状态 (3:待发货)
                ]);
                //创建发货明细
                $delivery->detail()->createMany($details);
                //创建发货地址
                $delivery->receiver()->create([
                    'order_no'   => $customerOrderObj->order_no ?? '',
                    'country'    => $customerOrderObj->receiver->country ?? '',
                    'receiver'   => $customerOrderObj->receiver->receiver ?? '',
                    'address'    => $customerOrderObj->receiver->address ?? '',
                    'state'      => $customerOrderObj->receiver->state ?? '',
                    'city'       => $customerOrderObj->receiver->city ?? '',
                    'postcode'   => $customerOrderObj->receiver->postcode ?? '',
                    'phone'      => $customerOrderObj->receiver->phone ?? '',
                ]);
                if(!$delivery) return ['status' => false, 'message' => '创建FBA发货单失败!'];
                if(!$delivery->detail) return ['status' => false, 'message' => '创建FBA发货单明细异常!'];
                if(!$delivery->receiver) return ['status' => false, 'message' => '创建FBA发货单地址异常!'];
                Logs::logs(Logs::CUSTOMER_ORDER_FBA,"创建FBA发货单：{$deliveryNo}", $delivery->id);
            }

            //更新订单明细
            foreach ($detail as $pskuId => $item){
                $orderDetailObj = CustomerOrderDetails::query()->find($item['order_detail_id']);
                if($orderDetailObj->status == CustomerOrderDetails::ORDER_DELIVERY_CANCEL) continue;

                $orderDetailStatus = CustomerOrderDetails::getOrderDetailStatus($orderDetailObj, $item['apply_num']);
                $orderDetailObj->status = $orderDetailStatus; //申请状态 (1:未申请 2:部分申请 3:完全申请 4:已取消)
                $orderDetailObj->save();
            }

            //DB::commit();
            return ['status' => true, 'message' => 'FBA发货成功'];
        //}catch (\Exception $e){
        //    report($e);
        //    DB::rollBack();
        //    return ['status' => false, 'message' => $e->getMessage()];
        //}
    }

    /**
     * 创建海外仓发货单
     * @param $delivery_type
     * @param $customerOrderObj
     * @param $detail
     * @return array
     */
    private function doWarehouseDelivery($delivery_type, $customerOrderObj, $detail){

        //客户订单
        if(!$customerOrderObj) return ['status' => false, 'message' => '客户订单异常!'];
        //发货站点
        if(!$customerOrderObj->area_id) return ['status' => false, 'message' => '发货站点异常!'];
        //发货国家
        if(!$customerOrderObj->country_id) return ['status' => false, 'message' => '发货国家异常!'];

        //验证实际发货单号(批次)
        $_deliveryOrderNo = CustomerDeliveryDetail::query()
            ->where(['order_no' => $customerOrderObj->order_no])
            ->orderBy('id', 'DESC')
            ->limit(1)
            ->value('delivery_order_no');
        $deliveryOrderNo = formatStrOrderNo($_deliveryOrderNo) ?? $customerOrderObj->order_no;

        //组装发货明细数据
        $deliveryDetail = [];
        foreach ($detail as $pskuId => $item){
            $orderDetailObj = CustomerOrderDetails::query()->find($item['order_detail_id']);
            if($orderDetailObj->status == CustomerOrderDetails::ORDER_DELIVERY_CANCEL) continue;

            //发货明细数据
            $deliveryDetail[$customerOrderObj->order_no][] = [
                'order_no'          => $customerOrderObj->order_no, //订单号
                'delivery_order_no' => $deliveryOrderNo, //实际发货订单号
                'order_detail_id'   => $item['order_detail_id'], //订单明细id
                'psku_id'           => $pskuId,
                'seller_sku'        => '',
                'plat_id'           => $customerOrderObj->plat_id,
                'plat_sku'          => $orderDetailObj->plat_sku ?? '',
                'apply_num'         => $item['apply_num'] ?? 0,
                'ship_num'          => $item['apply_num'] ?? 0,
                'account_id'        => $item['account_id'],
                'warehouse_id'      => $item['warehouse_id'],
                'apply_remarks'     => $item['apply_remarks'] ?? '',
                'status'            => CustomerDeliveryDetail::STATUS_DELIVERY_NO, //FBA发货,默认发货明细状态 (3:待发货)
                'delivery_type' => $delivery_type,
            ];
        }
        if(empty($deliveryDetail)) return ['status' => false, 'message' => '暂无可发货产品!'];

        //DB::beginTransaction();
        //try{
            //发货
            foreach($deliveryDetail as $details){
                //创建发货单
                $deliveryNo = SerialNo::getOOSNo();
                $delivery = CustomerDelivery::query()->create([
                    'delivery_no'   => $deliveryNo,
                    'order_no'      => $customerOrderObj->order_no,
                    'order_at'      => $customerOrderObj->order_at,
                    'plat_id'       => $customerOrderObj->plat_id,
                    'area_id'       => $customerOrderObj->area_id,
                    'country_id'    => $customerOrderObj->country_id,
                    'seller_id'     => Admin::user()->id ?? 0,
                    'delivery_type' => $delivery_type,
                    'status'        => CustomerDelivery::STATUS_DELIVERY_NO,  //海外仓发货,默认发货单状态 (3:待发货)
                ]);
                //创建发货明细
                $delivery->detail()->createMany($details);
                //创建发货地址
                $delivery->receiver()->create([
                    'order_no'   => $customerOrderObj->order_no ?? '',
                    'country'    => $customerOrderObj->receiver->country ?? '',
                    'receiver'   => $customerOrderObj->receiver->receiver ?? '',
                    'address'    => $customerOrderObj->receiver->address ?? '',
                    'state'      => $customerOrderObj->receiver->state ?? '',
                    'city'       => $customerOrderObj->receiver->city ?? '',
                    'postcode'   => $customerOrderObj->receiver->postcode ?? '',
                    'phone'      => $customerOrderObj->receiver->phone ?? '',
                ]);
                if(!$delivery) return ['status' => false, 'message' => '创建海外仓发货失败!'];
                if(!$delivery->detail) return ['status' => false, 'message' => '创建海外仓发货明细异常!'];
                if(!$delivery->receiver) return ['status' => false, 'message' => '创建海外仓发货地址异常!'];
                Logs::logs(Logs::CUSTOMER_ORDER_ABROAD,"创建海外仓发货单：{$deliveryNo}", $delivery->id);
            }

            //更新订单明细
            foreach ($detail as $pskuId => $item){
                $orderDetailObj = CustomerOrderDetails::query()->find($item['order_detail_id']);
                if($orderDetailObj->status == CustomerOrderDetails::ORDER_DELIVERY_CANCEL) continue;

                $orderDetailStatus = CustomerOrderDetails::getOrderDetailStatus($orderDetailObj, $item['apply_num']);
                $orderDetailObj->status = $orderDetailStatus; //申请状态 (1:未申请 2:部分申请 3:完全申请 4:已取消)
                $orderDetailObj->save();
            }

            //DB::commit();
            return ['status' => true, 'message' => '海外仓发货成功'];
        //}catch (\Exception $e){
        //    report($e);
        //    DB::rollBack();
        //
        //    return ['status' => false, 'message' => $e->getMessage()];
        //}
    }

    /**
     * 创建国内仓发货单
     * @param $delivery_type
     * @param $customerOrderObj
     * @param $detail
     * @return array
     */
    private function doCnDelivery($delivery_type, $customerOrderObj, $detail){

        //客户订单
        if(!$customerOrderObj) return ['status' => false, 'message' => '客户订单异常!'];
        //发货站点
        if(!$customerOrderObj->area_id) return ['status' => false, 'message' => '发货站点异常!'];
        //发货国家
        if(!$customerOrderObj->country_id) return ['status' => false, 'message' => '发货国家异常!'];

        //验证实际发货单号(批次)
        $_deliveryOrderNo = CustomerDeliveryDetail::query()
            ->where(['order_no' => $customerOrderObj->order_no])
            ->orderBy('id', 'DESC')
            ->limit(1)
            ->value('delivery_order_no');
        $deliveryOrderNo = formatStrOrderNo($_deliveryOrderNo) ?? $customerOrderObj->order_no;

        //组装数据
        $deliveryDetail = [];
        foreach($detail as $pskuId => $item){
            $orderDetailObj = CustomerOrderDetails::query()->find($item['order_detail_id']);
            if($orderDetailObj->status == CustomerOrderDetails::ORDER_DELIVERY_CANCEL) continue;

            //发货明细数据
            $deliveryDetail[$customerOrderObj->order_no][] = [
                'order_no'          => $customerOrderObj->order_no,
                'delivery_order_no' => $deliveryOrderNo, //实际发货订单号
                'order_detail_id'   => $orderDetailObj->id,
                'psku_id'           => $pskuId,
                'plat_id'           => $customerOrderObj->plat_id ?? 0,
                'plat_sku'          => $orderDetailObj->plat_sku ?? '',
                'apply_num'         => $item['apply_num'] ?? 0,
                'apply_remarks'     => $item['apply_remarks'] ?? '',
                'status'            => CustomerDeliveryDetail::STATUS_READY_NO, //国内发货,默认发货明细状态 (1:待备货)
                'delivery_type' => $delivery_type,   //发货方式 (3:国内)
            ];
        }
        if(empty($deliveryDetail)) return ['status' => false, 'message' => '无可申请发货产品!'];

        //DB::beginTransaction();
        //try{
            //发货
            foreach($deliveryDetail as $details){

                $flag = false;
                foreach ($details as $_item){
                    //更新国内库存（库存扣减优先级：out > 其它站点 > public）
                    $inventoryCnFlag = self::saveCnInventory($_item, $customerOrderObj->order_no);
                    if ($inventoryCnFlag == false) break;

                   $flag = true;
                }
                if(!$flag) return ['status' => false, 'message' => '库存更新失败!'];

                //站外与公共库存的站点id/国家id
                $outAreaId = SysArea::getSysOutAreaIdByArea();
                $outCountryId = SysCountry::getCountryIdsByAreaId($outAreaId);
                if ($outAreaId == 8) { //站外ID
                    $outCountryId = 14; //站外国家
                }
                //创建发货
                $deliveryNo = SerialNo::getOPDNo();
                $delivery = CustomerDelivery::query()->create([
                    'delivery_no'   => $deliveryNo,
                    'order_no'      => $customerOrderObj->order_no ?? '',
                    'order_at'      => $customerOrderObj->order_at ?? '',
                    'plat_id'       => $customerOrderObj->plat_id,
                    'area_id'       => $outAreaId,
                    'country_id'    => $outCountryId,
                    'seller_id'     => Admin::user()->id ?? 0,
                    'delivery_type' => $delivery_type,
                    'status'        => CustomerDelivery::STATUS_READY_NO,  //国内发货,默认发货单状态 (1:待备货)
                ]);
                //创建发货明细
                $delivery->detail()->createMany($details);
                //创建发货地址
                $delivery->receiver()->create([
                    'order_no'   => $customerOrderObj->order_no ?? '',
                    'country'    => $customerOrderObj->receiver->country ?? '',
                    'receiver'   => $customerOrderObj->receiver->receiver ?? '',
                    'address'    => $customerOrderObj->receiver->address ?? '',
                    'state'      => $customerOrderObj->receiver->state ?? '',
                    'city'       => $customerOrderObj->receiver->city ?? '',
                    'postcode'   => $customerOrderObj->receiver->postcode ?? '',
                    'phone'      => $customerOrderObj->receiver->phone ?? '',
                ]);
                if(!$delivery) return ['status' => false, 'message' => '创建国内发货失败!'];
                if(!$delivery->detail) return ['status' => false, 'message' => '创建国内发货明细异常!'];
                if(!$delivery->receiver) return ['status' => false, 'message' => '创建国内发货地址异常!'];
                Logs::logs(Logs::CUSTOMER_ORDER_CN, "创建国内发货单：{$deliveryNo}", $delivery->id);
            }

            //更新订单详情
            foreach($detail as $pskuId => $item){
                $orderDetailObj = CustomerOrderDetails::query()->find($item['order_detail_id']);
                if($orderDetailObj->status == CustomerOrderDetails::ORDER_DELIVERY_CANCEL) continue;

                $orderDetailStatus = CustomerOrderDetails::getOrderDetailStatus($orderDetailObj, $item['apply_num']);
                $orderDetailObj->status = $orderDetailStatus; //订单申请状态 (1:未申请 2:部分申请 3:完全申请 4:已取消)
                $orderDetailObj->save();
            }

            //DB::commit();
            return ['status' => true, 'message' => '国内发货成功'];
        //}catch (\Exception $e){
        //    report($e);
        //    DB::rollBack();
        //    return ['status' => false, 'message' => $e->getMessage()];
        //}
    }

    /**
     * 获取库存 （库存扣减优先级：out > 其它站点 > public）
     * @param $_item
     * @param $orderNo
     * @return bool
     */
    public static function saveCnInventory($_item, $orderNo){

        $inventoryCnFlag = false;
        $productSku = ProductSku::getModelById($_item['psku_id']);
        if(!$productSku){
            return $inventoryCnFlag;
            //throw new \Exception('订单【' . $orderNo . '】, 【'. $productSku->psku_code. '】, 产品不存在!');
        }

        //国内仓库存
        $timely = Timely::getInstant($_item['psku_id']);
        if($timely < $_item['apply_num']){
            return $inventoryCnFlag;
            //throw new \Exception('订单【' . $orderNo . '】, 【'. $_item['psku_id']. '】, 库存不足!');
        }

        //站外与公共库存的站点id
        $outId = SysArea::getSysOutAreaIdByArea();
        $publicId = SysArea::getSysAreaIdByArea();

        //out(站外)
        $outInstant = AreaCn::getInstant($outId, $_item['psku_id']);
        $applyNum = $_item['apply_num'];
        $outAreaCn = AreaCn::getAreaCn($outId, $_item['psku_id']);
        if ($outAreaCn && $outAreaCn->instant > $applyNum) {
            $diffOutInstant = min($outInstant, $applyNum); //扣除（out）站外库存数量
            $outAreaCn->instant -= $diffOutInstant;
            $outAreaCn->reserve += $_item['apply_num'];
            if(!$outAreaCn->save()){
                return $inventoryCnFlag;
                //throw new \Exception('操作失败1-站外库存异常!');
            }
            $applyNum -= $diffOutInstant; //扣除（out）站外库存后的数量(剩余未满足的数量)
        }

        //其它站点
        if($applyNum > 0){
            $inventory = InventoryCn::query()
                ->where('instant','>',0)
                ->whereNotIn('area_id', [$outId,$publicId])
                ->where('psku_id',$_item['psku_id'])
                ->orderBy('instant','DESC')
                ->get();
            foreach($inventory as $_inventory){
                $inventoryNum = min($applyNum, $_inventory->instant);//可发数量（站点）
                $_inventory->instant -= $inventoryNum;
                if(!$_inventory->save()){
                    return $inventoryCnFlag;
                    //throw new \Exception('操作失败-3-'.$_inventory->area_id.'!');
                }
                $applyNum -= $inventoryNum;
                if($applyNum == 0){
                    break;
                }
            }
        }

        //public
        if($applyNum > 0){
            $publicInstant = PublicCn::getInstant($_item['psku_id']);
            if($publicInstant < $applyNum){
                return $inventoryCnFlag;
                //throw new \Exception('订单【' . $orderNo . '】, 【'. $_item['psku_id']. '】, 公共库存库存不足!');
            }else{
                $publicCn = PublicCn::getPublicCn($_item['psku_id']);
                if ($publicCn) {
                    $publicCn->instant -= $applyNum;
                    if(!$publicCn->save()){
                        return $inventoryCnFlag;
                        //throw new \Exception('操作失败2-公共库存异常!');
                    }
                    $areaInventory = InventoryCn::query()
                        ->where('area_transit','>',0)
                        ->whereNotIn('area_id', [$outId,$publicId])
                        ->where('psku_id',$_item['psku_id'])
                        ->orderBy('area_transit','DESC')
                        ->get();
                    $tempTransit = $applyNum;
                    foreach($areaInventory as $_areaInventory){
                        $tempNum = min($tempTransit, $_areaInventory->area_transit);
                        $_areaInventory->area_transit -= $tempNum;
                        if(!$_areaInventory->save()){
                            return $inventoryCnFlag;
                            //throw new \Exception('操作失败-3-'.$_areaInventory->area_id.'在途扣减失败!');
                        }
                        $tempTransit -= $tempNum;
                        if($tempTransit == 0){
                            break;
                        }
                    }
                }
            }
        }

        $inventoryCnFlag = true;
        return $inventoryCnFlag;
    }

    /**
     * 查看收货详情
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function viewDetail($id){
        $customerOrder = CustomerOrder::query()->findOrFail($id);
        return view('customer-delivery.delivery-demand.modal-detail', compact('customerOrder'));
    }

    /**
     * 添加产品
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function addListOutOrderSku($id){
        return view('customer-delivery.delivery-demand.modal-sku', compact('id'));
    }

    /**
     * 添加产品项
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function doAddOutOrderSku($param){
        try{
            $customerOrder = CustomerOrder::query()->findOrFail($param['id']);
            if (empty($customerOrder)) return response()->json(['status' => false, 'message' => '订单异常！']);
            unset($param['id']);

            DB::beginTransaction();
            $flag = false;
            foreach ($param as $val){
                $count = CustomerOrderDetails::query()
                    ->where('order_no', $customerOrder->order_no)
                    ->where('psku_id', $val['psku_id'])
                    ->count();
                if($count > 0) continue;
                $flag1 = CustomerOrderDetails::query()->create([
                    'order_no'  => $customerOrder->order_no,
                    'psku_id'   => $val['psku_id'],
                    'plat_sku'  => CustomerOrderDetails::getOrderPlatsku($customerOrder->order_no, $val['psku_id']),
                    'order_num' => $val['order_num'],
                ]);
                if(!$flag1){
                    $flag = false;
                    break;
                }
                $flag = true;
            }
            if(!$flag){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }else{
                DB::commit();
                return response()->json(['status' =>true, 'message' => '操作成功！']);
            }
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    /**
     * 取消产品项
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancelOutOrderItem($id){
        try{
            $orderDetails = CustomerOrderDetails::query()->find($id);
            if($orderDetails->status == CustomerOrderDetails::ORDER_DELIVERY_CANCEL){
                return response()->json(['status' => false, 'message' => '状态有误！']);
            }

            DB::beginTransaction();
            $orderDetails->status = CustomerOrderDetails::ORDER_DELIVERY_CANCEL; //状态 (4:已取消)
            if(!$orderDetails->save()){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '取消失败！']);
            }else{
                DB::commit();
                return response()->json(['status' =>true, 'message' => '取消成功！']);
            }
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    /**
     * 启用产品项
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function enableOutOrderItem($id){
        try{
            $orderDetails = CustomerOrderDetails::query()->find($id);
            if($orderDetails->status != CustomerOrderDetails::ORDER_DELIVERY_CANCEL){
                return response()->json(['status' => false, 'message' => '状态有误！']);
            }

            DB::beginTransaction();
            $num = $orderDetails->apply_num;
            if($num == 0){
                $orderDetails->status = CustomerOrderDetails::ORDER_DELIVERY_NO; //申请状态(1:未申请)
            }elseif($num < $orderDetails->order_num){
                $orderDetails->status = CustomerOrderDetails::ORDER_DELIVERY_PART; //申请状态(2:部分申请)
            }else{
                $orderDetails->status = CustomerOrderDetails::ORDER_DELIVERY_YES; //申请状态(3:完全申请)
            }
            if(!$orderDetails->save()){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '启用失败！']);
            }else{
                DB::commit();
                return response()->json(['status' =>true, 'message' => '启用成功！']);
            }

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    /**
     * 删除产品项
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function delOutOrderSku($id){
        try{
            $orderDetails = CustomerOrderDetails::query()->find($id);
            if(!in_array($orderDetails->status, [CustomerOrderDetails::ORDER_DELIVERY_NO, CustomerOrderDetails::ORDER_DELIVERY_CANCEL])){
                return response()->json(['status' => false, 'message' => '状态有误！']);
            }

            $count = CustomerOrderDetails::query()
                ->where('order_no', $orderDetails->order_no)
                ->where('id', '<>', $id)
                ->count();
            if($count == 0)return response()->json(['status' => false, 'message' => '请至少保留一个产品！']);

            DB::beginTransaction();
            if(!$orderDetails->delete()){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '删除商品失败！']);
            }else{
                DB::commit();
                return response()->json(['status' => true, 'message' => '删除产品成功！']);
            }
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    /**
     * 删除订单
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function delOutOrder($id){
        try{
            DB::beginTransaction();
            $customerOrder = CustomerOrder::query()->findOrFail($id);

            if($customerOrder->detail->count() > 0){
                return response()->json(['status' => false, 'message' => '已存在下游单据！']);
            }
            if(!$customerOrder->delete()){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '删除订单失败！']);
            }else{
                DB::commit();
                return response()->json(['status' =>true, 'message' => '删除订单成功！']);
            }
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    /**
     * 创建消费者订单 (手动,添加订单(自建))
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function createCustomerOrder($param){

        $receiver = $param['receiver'];
        $detail = $param['detail'];
        $orderChannel = $param['order_channel'];
        $orderType = $param['order_type'];
        $platId = $param['plat_id'];
        $countryId = $param['country_id'];
        if(!$orderChannel || !$orderType || !isset($platId) || !$countryId){
            return response()->json(['status' => false, 'message' => '订单参数必选,不能为空']);
        }
        if (!in_array(isset($platId), SysPlat::options()->toArray())) {
            return response()->json(['status' => false, 'message' => '平台异常!']);
        }

        //发货国家
        $countryObj = SysCountry::getModelById($countryId);
        if(empty($countryObj)) return response()->json(['status' => false, 'message' => '发货国家异常!']);

        //发货站点 (从关联表中获取对应国家的站点)
        $areaId = SysCountry::getAreaIdByCountryId($countryObj->id);
        if(empty($areaId)) return response()->json(['status' => false, 'message' => '发货站点异常!']);


        $orderNo = $param['order_no'] ?? SerialNo::getOCnNo(); //客户订单(国内erp手工自建单)，生成客户订单号
        $orderCount = CustomerOrder::query()->where(['order_no'=>$orderNo])->count();
        if($orderCount > 0) return response()->json(['status' => false, 'message' => '订单号已存在, 请重新选择单号']);

        //验证订单明细，并组装明细
        $orderDetailData = [];
        foreach($detail as $item) {
            $count = CustomerOrderDetails::query()
                ->where('order_no', $orderNo)
                ->where('psku_id', $item['psku_id'])
                ->count();
            if($count > 0) break;

            $orderDetailData[] = [
                'plat_id'   => $platId,
                'psku_id'   => $item['psku_id'],
                'plat_sku'  => CustomerOrderDetails::getOrderPlatsku($orderNo, $item['psku_id']),
                'order_num' => intval($item['apply_num']) ?? 0,
                'status'    => CustomerOrderDetails::ORDER_DELIVERY_NO, //订单申请状态 (1:未申请发货)
            ];
        }
        if(empty($orderDetailData)) return response()->json(['status' => false, 'message' => '产品不能为空,请添加产品!']);

        //DB::beginTransaction();
        //try{
            //收货人信息
            $receiverData = [
                'order_no'   => $orderNo,
                'country'   => $receiver['country'],
                'receiver'  => $receiver['receiver'],
                'address'   => $receiver['address'],
                'state'     => $receiver['state'],
                'city'      => $receiver['city'],
                'postcode'  => $receiver['postcode'],
                'phone'     => $receiver['phone'],
            ];

            //创建相关订单信息
            $orderObj = CustomerOrder::query()->create([
                'order_no'      => $orderNo,
                'order_at'      => date('Y-m-d H:i:s', time()),
                'order_channel' => $orderChannel,   //订单渠道(1.C端，2.B端)
                'order_type'    => $orderType,  //订单类型(1.订单，2.寄样)
                'plat_id'       => $platId,  //订单平台 (0:无 1:FBA亚马逊 2:shopify 3:乐天)
                'country_id'    => $countryObj->id,  //发货国家
                'country_code'  => $countryObj->country,  //发货国家编码
                'area_id'       => $areaId,  //发货站点
            ]);
            $orderObj->detail()->createMany($orderDetailData);
            $orderObj->receiver()->create($receiverData);
            if(!$orderObj) throw new \Exception('订单录入失败!');
            Logs::logs(Logs::CUSTOMER_ORDER, "创建消费订单(自建)：{$orderNo}", $orderObj->id);

            //DB::commit();
            return response()->json(['status' =>true, 'message' => '操作成功!']);

        //}catch (\Exception $e){
        //    DB::rollBack();
        //    report($e);
        //    return response()->json(['status' => false, 'message' => $e->getMessage()]);
        //}
    }

}
